import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import RegisterView from '@/views/RegisterView.vue'
import ProfileView from '@/views/ProfileView.vue'
import RankingView from '@/views/RankingView.vue'
import AboutView from '@/views/AboutView.vue'
import NowView from '@/views/NowView.vue'
import DetailView from '@/views/TourDetail.vue'
import AddTourView from '@/views/AddTourView.vue'
import MonthlyRecommendationView from '@/views/MonthlyRecommendationView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView
  },
  {
    path: '/profile',
    name: 'profile',
    component: ProfileView,
    meta: { requiresAuth: true }
  },
  {
    path: '/ranking',
    name: 'ranking',
    component: RankingView,
    meta: { requiresAuth: true }
  },
  {
    path: '/detail',
    name: 'detail',
    component: DetailView,
    meta: { requiresAuth: true }
  },
  {
    path: '/add',
    name: 'add',
    component: AddTourView,
    meta: { requiresAuth: true }
  },
  {
    path: '/monthlyRecommendation',
    name: 'monthlyRecommendation',
    component: MonthlyRecommendationView,
    meta: { requiresAuth: true }
  },
  {
    path: '/now',
    name: 'now',
    component: NowView,
    meta: { requiresAuth: true }
  },
]


const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  const hasToken = localStorage.getItem('token'); // 检查本地缓存中是否存在 token
  if (to.meta.requiresAuth && !hasToken) {
    next('/login'); // 如果需要认证且没有 token，则重定向到登录页面
  } else {
    next(); // 继续导航
  }
});

export default router;
